package photobox

import com.sun.image.codec.jpeg.JPEGCodec
import grails.converters.JSON
import photobox.account.ApplyForPhotographer
import photobox.account.Member
import photobox.account.Notice
import photobox.account.Region
import photobox.account.User
import photobox.account.UserBrowse
import photobox.order.Order
import photobox.order.OrderItem
import photobox.photo.Photo
import photobox.utils.ImageUtils
import photobox.utils.SendSms

import javax.imageio.ImageIO
import java.awt.image.BufferedImage

class MemberController extends BaseController {
    def memberService
    static validateCode
    def applyForPhotographerService
    def login(){
        def r = memberService.loginCheck(params,session)
        render(r)
    }
    def register() {
       // def url = request.getHeader("referer");
        if(session.userId != null){
            redirect(controller: 'member',action: 'personCenter')
        }
        def reqURI = request.getRequestURI();
        def strQuery = request.getQueryString();
    }

    def success() {
        if(session.userId==null){
            redirect(controller: "home" ,action:"index")
        }
        def userId = params["userId"]
        [userId: userId]
    }
    def sendSms(cellPhone){
        //http://www.smsbao.com/sms?u=USERNAME&p=PASSWORD&m=PHONE&c=CONTENT
        //用户名99tucang        密码((tucang

        def sms = new SendSms()
        sms.addMobiles(cellPhone)
        def r = sms.sendMsg(validateCode)
        println(r)
    }
    def sendMail(){
        sendMail {
            async false
            from "suke111@163.com"
            to   "3063388403@qq.com"
            subject  "baochun error: "
            body  '速客修改密码22222222222'
        }
    }

    def personal() {
        if(session.userId==null){
            redirect(controller: "home" ,action:"index")
        }else {

            def member = Member.get(session.userId)
            def cityList = new Region()
            def districtList = new Region()
            def provinceList = Region.findAllByRegionLevel(2)

            if (member.address?.size() == 0) {
                cityList = null
                districtList = null
            } else {
                cityList = Region.findAllByPid(member.address[0].province.id)
                districtList = Region.findAllByPid(member.address[0].city.id)
            }

            [user: member, provinceList: provinceList, cityList: cityList, districtList: districtList]
        }

    }

    def listByCity() {
        render g.select(name: "city", id: "form-city", optionKey: "id", optionValue: "name", class: "width-50",
                from: Region.findAllByPid(params.provinceId),
                noSelection: ["":"--请选择--"],
                onchange: remoteFunction(controller: 'member', action: 'listByDistrict', params: '\'cityId=\'+this.value', update: 'district')) + "市"
    }

    def listByDistrict() {
        render g.select(name: "district", id: "form-district", optionKey: "id", optionValue: "name", class: "width-50",
                from: Region.findAllByPid(params.cityId),
                noSelection: ["":"--请选择--"]) + "区(县)"
    }

    def getValidateCode() {
        def cellPhone = params.cellPhone
        if (!cellPhone) {
            render ([status: 0, message: "请填写您的手机号码以便获取验证码"] as JSON)
            return
        }
        def r = ""
        def random = new Random()
        for (int i = 0; i < 4; i++) {
            r += random.nextInt(10)
        }
        validateCode = r
        sendSms(cellPhone)
        render ([status: 1, message: validateCode] as JSON)
    }

    def save() {
        if (validateCode == params.validateCode?.trim()) {
            def user = memberService.createUser(params,session)
            render([error: 0, message: "注册成功", userId: user.id] as JSON)
        } else {
            render([error: 1, message: "验证码错误,请获取验证码"] as JSON)
        }


    }
    def isUnique(){
        def member = Member.findByUsername(params.username)
        def memberId = member ? member.id : ''
        render([memberId: memberId] as JSON)
    }

    def update() {

        if (session.userId) {
            memberService.updateUser(params,session.userId)
            redirect(action: 'personal')
        }else{
            redirect(controller: 'home', action: 'index')
        }

    }

    def saveIocn() {
        String pictureUrl = uploadImage()
        //render([status:1,msg:"ok", img:pictureUrl] as JSON)
        memberService.saveIcon(pictureUrl,session)
        render([status:1,msg:"ok", img:pictureUrl] as JSON)
    }
    def uploadImage(){//上傳用户头像
        BufferedImage
        ImageIO
        JPEGCodec
        def filePathName
        def path
        def f = request.getFile ('file')//获取前台页面表单控//中的文件名称
        String pictureUrl =  request.getSession().getServletContext().getRealPath('images');
        if (!f.empty) {
            Date  d= new Date();
            String dateString=  d.format ("yyyy-mm-dd-hh-ss")
            String  fileProName=f.getOriginalFilename ()
            String extension = fileProName.split('\\.')[-1]  //截取获取文0. //件名的后缀
            filePathName = pictureUrl+"/" + dateString+"."+extension
            f.transferTo (new File(filePathName))
            path = "images/"+dateString+"_100."+extension
            ImageUtils.makeSmallImage(filePathName,  pictureUrl+"/"+dateString+"_100."+extension ,100)
            ImageUtils.makeSmallImage(filePathName,  pictureUrl+"/"+dateString+"_50."+extension ,50)
        }
        return  path   //返回文件名称
    }
    def updatePassword(){
        if(session.userId){
            def f =  memberService.updatePassword(params, session.userId)
            render ([message:f] as JSON)
        }else {
            render ([message:'请先登录'] as JSON)
        }

    }

    def personPhoto(){

        def member = Member.get(session.userId)
        def photo = Photo.findAllByUser(member)
        ArrayList imagePath = photo.originImagePath

       render([imagePath:imagePath,photo:photo] as JSON)
    }
    def news(){
        if(session.userId==null){
            redirect(controller: "home" ,action:"index")
        }
       def user = User.findById(session.userId)
       def noticeAll = Notice.findAllByIsReadAndUser(0,user)
       if(noticeAll){
           memberService.updateNoticeReaded(session.userId)
       }
       if(params.json && session.userId){
            def max = params.max?:8
            def offset = params.offset?:0
            def member = Member.get(session.userId)
            def hql_2 = "from Notice as N where user="+member.id+""
            def notice = Notice.executeQuery(hql_2,[max:max, offset:offset])
            def noticeChange = Notice.executeQuery(hql_2)
            def noRead = 0
            def o = max.toInteger() +  offset.toInteger()
            render( [member:member,notice:notice,offset: o,max:max] as JSON)
        }
    }

    def readStatus(){
        if(session.userId){
            def member = Member.get(session.userId)
            def hql_2 = "from Notice as N where user="+member.id+""
            def notice = Notice.executeQuery(hql_2)
            def noRead = 0
            notice.each {
                if(it.isRead == 0){
                    noRead = noRead +1
                }
            }
            render( [member:member,notice:notice,noRead:noRead] as JSON)
        }
    }

    def signQuit(){
        session.removeAttribute("userId")
        session.removeAttribute("orderItems")

        if(session.getAttribute("userId")==null){
            render([quitMessage:"您已退出"] as JSON)
        }else {
            render([quitMessage:"请重新退出"] as JSON)
        }

//        redirect(controller: "home" ,action:"index")
    }
    def forgetPwd(){

    }
    def sendPwd(){

        if (validateCode == params.validateCode) {
            def user = User.findByUsername(params.username)
            if(user){
                sendMail {
                    async false
                    from "suke111@163.com"
                    to   "455433425@qq.com"
                    subject  "baochun error: "
                    body  "http://localhost:8080/photobox/member/newPwd?id="+user.id+""
                }
                render([ message: "请去邮箱跳转页面"] as JSON)
            }else{
                render([ message: "用户名不存在"] as JSON)
            }
        } else  {
            render([ message: "验证码错误,请获取验证码"] as JSON)
        }
    }
    def personCenter(){
        if(session.userId==null){
            redirect(controller: "home" ,action:"index")
        }
        //计算订单数量、交易金额
        def user = User.get(session.userId)
        def ttList = Order.findAllByUser(user)
        def orderCount = ttList.size()
        def cash = 0
        ttList.each {
            if(it.orderStatus>=20){
                cash += it.totalPrice
            }
        }
        if(params.json){
            def max = params.max
            def offset = params.offset
            def member = Member.get(session.userId)
            def hql = "from Photo where user_id=" + session.userId
            //def photoList = Photo.findAllByKeywordsLike(keyword, [max:max, offset:offset])
            def photoList = Photo.executeQuery(hql, [], [max:max, offset:offset])
            def photoLists = []
            photoList.each{
                photoLists.push(
                        id: it.id,
                        smallImagePath: it.smallImagePath,
                        name: it.name,
                        price: it.price,
                        username: it.user?.username
                )
            }
            def photoCount = Photo.executeQuery(hql).size()
            def o = max.toInteger() +  offset.toInteger()
            render( [member:member,photoList:photoLists, offset: o,max:max,photoCount:photoCount] as JSON)
        }
        [orderCount:orderCount,cash:cash]

//        def member = Member.get(session.userId)
//        def photo = Photo.findAllByUser(member)
//        def photoPathList = photo.originImagePath
//
//        [member:member,photo:photo,photoPathList:photoPathList]
    }
    def browserHistory(){
        if(session.userId==null){
            redirect(controller: "home" ,action:"index")
        }
        if(params.json){
            def max = params.max
            def offset = params.offset
            def user = User.get(session.userId)
            def hql_1 = "from UserBrowse as U where U.user="+user.id+""
            def userBrowse = UserBrowse.executeQuery(hql_1,[max:max,offset: offset])
            def photoList = []
            userBrowse.each{
                photoList.push(
                        id: it.photo?.id,
                        smallImagePath: it.photo?.smallImagePath,
                        name: it.photo?.name,
                        price: it.photo?.price,
                        username:it.photo.user.username
                )

            }
            def o = max.toInteger() +  offset.toInteger()
            render( [photoList:photoList, offset: o,max:max] as JSON)
        }
    }
    def purchasedPhoto(){
        if(session.userId==null){
            redirect(controller: "home" ,action:"index")
        }
        def user = User.get(session.userId)
        def ttList = Order.findAllByUserAndOrderStatusGreaterThanEquals(user,Order.ORDER_STATUS_PAID)
        def totalMoney = 0
        ttList.each{
            totalMoney += it.totalPrice;
        }

        if(params.json){
            def max = params.max
            def offset = params.offset

            def hql_1 = "from Order as U where U.orderStatus >=20 AND U.user="+user.id+""
            def order = Order.executeQuery(hql_1,[max:max,offset: offset])
            def photoLists = []
            def photoIds = []

            order.each{

                it.items.each{

//                    if(!(it.photo?.id in photoIds)){
//                        photoIds.push(it.photo?.id)
                        photoLists.push(
                                id: it.photo?.id,
                                smallImagePath: it.photo?.smallImagePath,
                                name: it.photo?.name,
                                price: it.photo?.price,
                                username: it.photo.user?.username,
                                num :it.number
                        )
//                    }

                }
                //println(photoIds)    一个订单内有多个订单项 可能会有相同的作品
            }
            def o = max.toInteger() +  offset.toInteger()

            render( [photoList:photoLists, offset: o,max:max] as JSON)
        }
        [totalPay:Math.round(totalMoney)]
    }
    /*
    申请成为摄影师
     */
    def applyPhotographer (){
        applyForPhotographerService.saveApply(session)
        def applyForPhotographer = ApplyForPhotographer.findByUser(User.get(session.userId))
        applyForPhotographerService.saveNotice(applyForPhotographer)
        render(['message':'您已成功提交申请，请耐心等待管理员审核'] as JSON)
    }
   def newPwd(){
      def userId= params.id
       [userId:userId]
   }
    def saveNewPwd(){
        def f = memberService.savePassword(params)
        render([message:f] as JSON)

    }
    def clearBrowserHistory(){
        def member = Member.get(session.userId)
        def r = memberService.clearBrowserHistory(member)
        render([status: r] as JSON)
    }
}
